//
//  ViewModel.m
//  Project_Demo
//
//  Created by caoxiaozhu on 2018/7/25.
//  Copyright © 2018年 caoxiaozhu. All rights reserved.
//

#import "ViewModel.h"

@implementation ViewModel

-(instancetype)init{
    if (self = [super init]) {
        [self setup];
    }
    return self;
}


-(void)setup{
    
    self.loginButtonEnableSignal = [RACSignal combineLatest:@[RACObserve(self, loginName),RACObserve(self, password)] reduce:^id (NSString *userName,NSString *psd){
        return @(userName.length > 5 && psd.length > 6);
    }];
    
//    RACSignal *
    
    RACSignal *loginCheckSignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        [subscriber sendNext:@"登录检查"];
        [subscriber sendCompleted];
        return nil;
    }];
    
    RACSignal *loginReuqetsSignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        
        AVUser *user = [AVUser user];
        user.username = self.loginName;
        user.password = self.password;
        
        [user signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            if (succeeded) {
                [subscriber sendNext:@"登录成功"];
                [subscriber sendCompleted];
            } else {
                self.loginName = @"leokaka1";
                [subscriber sendError:error];
            }
        }];
        
        return nil;
    }];

//    RACSignal *combineSignal = [loginCheckSignal concat:loginReuqetsSignal];
//    RACSignal *combineSignal  = [loginCheckSignal merge:loginReuqetsSignal];
    RACSignal *combineSignal = [loginCheckSignal then:^RACSignal * _Nonnull{
        return loginReuqetsSignal;
    }];

    self.loginCommad = [[RACCommand alloc]initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
        
        return combineSignal;
    }];
}


//正确的代码（参考）
-(void)test1{
    
    self.loginButtonEnableSignal = [RACSignal combineLatest:@[RACObserve(self, loginName),RACObserve(self, password)] reduce:^id (NSString *name,NSString *psd){
        return @(name.length > 5 && psd.length >6);
    }];
    
    RACSignal *loginCheckSignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        
        [subscriber sendNext:@"查询用户"];
        [subscriber sendCompleted];
        
        return nil;
    }];
    
   
    @weakify(self);
    RACSignal *loginRquest = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        
        [subscriber sendNext:@"登录成功"];
        [subscriber sendCompleted];
        
        return nil;
    }];
    
    RACSignal *combinSignal =  [[self.loginButtonEnableSignal concat: loginCheckSignal] concat: loginRquest];
    
    self.loginCommad = [[RACCommand alloc]initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
        
        return combinSignal;
    }];
}

@end
